<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店">
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 210px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="日期" :required="true">
              <a-range-picker
                :ranges="{
                  昨日: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                  近7天: [moment().subtract(8, 'days'), moment().subtract(1, 'days')],
                  本月: [moment().startOf('month'), moment().subtract(1, 'days')],
                }"
                v-model="orderDateRange"
                @change="handleChange"
                :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <!-- <a-button type="default" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls1('日营业数据')">导出日营业数据</a-button>
      <a-button type="primary" icon="download" :loading="exporting" @click="handleExportSalesBill('销售推账数据')"
        >导出销售推账数据</a-button
      >
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <span class="sum"
          >实收总金额(元) <span class="b">{{ sumModel.totalRealSaleAmount }}</span>
        </span>
        <span class="sum">=</span>
        <span class="sum"
          >开单总金额(元) <span class="b">{{ sumModel.totalSaleAmount }}</span>
        </span>
        <span class="sum">-</span>
        <span class="sum"
          >退款总金额(元) <span class="b">{{ sumModel.totalDisAmount }}</span>
        </span>
        <span class="sum">
          <a-divider type="vertical" style="background-color: rgba(0, 0, 0, 0.35)" />
        </span>
        <span class="sum"
          >商品销售总数(件) <span class="b">{{ sumModel.totalRealSaleCnt }}</span>
        </span>
        <span class="sum">=</span>
        <span class="sum"
          >开单销售总数(件) <span class="b">{{ sumModel.totalSaleCnt }}</span>
        </span>
        <span class="sum">-</span>
        <span class="sum"
          >退货总数(件) <span class="b">{{ sumModel.totalRefundCnt }}</span>
        </span>
        <span class="sum">
          <a-divider type="vertical" style="background-color: rgba(0, 0, 0, 0.35)" />
        </span>
        <span class="sum"
          >入库总件数 <span class="b">{{ sumModel.totalInStockCnt }}</span>
        </span>
        <span class="sum"
          >店余总计 <span class="b">{{ sumModel.totalRemainCnt }}</span>
        </span>
      </div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <DailySalesReport-modal ref="modalForm" @ok="modalFormOk"></DailySalesReport-modal>

    <!-- 推账-->
    <a-modal
      title="导出推账"
      style="top: 20px;"
      :width="500"
      v-model="exportVisible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :label-col="labelCol" :wrapper-col="wrapperCol" :model="exportModel">
            <a-form-model-item  label="品牌" prop="brandCode" :rules="[{ required: true, message: '请选择品牌' }]">
              <a-select v-model="exportModel.brandCode">
                <a-select-option v-for="item in brandList" :key="item.id" :value="item.brandCode">
                  {{ item.brandName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
      </a-form-model>
    </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { getAction, postAction, downFile } from '@/api/manage'
import { queryDepartTreeList1, queryMerchantBussList } from '@/api/api'
import DailySalesReportModal from './modules/DailySalesReportModal'

export default {
  name: 'DailySalesReport',
  mixins: [JeecgListMixin],
  components: {
    DailySalesReportModal,
  },
  data() {
    return {
      description: '日营业额报表',
      disableMixinCreated: true,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      orderDateRange: [],
      exporting: false,
      exportVisible: false,
      exportModel: {},
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      brandList: [],
      sumModel: {
        totalRealSaleAmount: 0,
        totalSaleAmount: 0,
        totalDisAmount: 0,
        totalRealSaleCnt: 0,
        totalSaleCnt: 0,
        totalRefundCnt: 0,
        totalInStockCnt: 0,
        totalRemainCnt: 0,
      },
      // 表头
      columns: [
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName',
        },
        {
          title: '门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '日结日期',
          align: 'center',
          dataIndex: 'daily',
        },
        {
          title: '实收金额',
          align: 'center',
          dataIndex: 'realSaleAmount',
          sorter: true,
        },
        {
          title: '开单金额',
          align: 'center',
          dataIndex: 'saleAmount',
        },
        {
          title: '退货金额',
          align: 'center',
          dataIndex: 'disAmount',
        },
        {
          title: '昨日结余',
          align: 'center',
          dataIndex: 'lastRemainCnt',
        },
        {
          title: '销售数量',
          align: 'center',
          dataIndex: 'realSaleCnt',
          sorter: true,
        },
        {
          title: '开单数量',
          align: 'center',
          dataIndex: 'saleCnt',
        },
        {
          title: '退货数量',
          align: 'center',
          dataIndex: 'refundCnt',
        },
        {
          title: '收货数量',
          align: 'center',
          dataIndex: 'checkInStockCnt',
        },
        {
          title: '返货数量',
          align: 'center',
          dataIndex: 'checkOutStockCnt',
        },
        {
          title: '调入',
          align: 'center',
          dataIndex: 'transInStockCnt',
        },
        {
          title: '调出',
          align: 'center',
          dataIndex: 'transOutStockCnt',
        },
        {
          title: '店余合计',
          align: 'center',
          dataIndex: 'remainCnt',
          sorter: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/report/daily/list',
        sumUrl: '/report/daily/sum',
        exportXlsUrl: '/report/daily/exportXls',
        exportSalesBillUrl: '/report/daily/exportSalesBill',
      },
    }
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    moment,
    init() {
      let lastDay = moment().subtract(1, 'days').format('YYYY-MM-DD')
      this.queryParam = {}
      this.$set(this.queryParam, 'beginDate', lastDay)
      this.$set(this.queryParam, 'endDate', lastDay)
      this.orderDateRange = [moment().subtract(1, 'days'), moment().subtract(1, 'days')]
      this.loadDepartTree()
      this.searchQuery1()
      this.loadBrandList()
    },
    loadBrandList() {
      this.brandList = []
      queryMerchantBussList({ 'bussType': 'BRAND' }).then((res) => {
        if (res.success) {
          for (let a of res.result) {
            this.brandList.push({ brandName: a.bussName, brandCode: a.bussCode })
          }

          this.$set(this.exportModel,'brandCode',this.brandList[0].brandCode)
        }
      })
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })

          // this.$set(this.queryParam,'selecteddeparts',[departList[0].id,'0'])
        }
      })
    },
    handleDetail(record) {
      this.$refs.modalForm.view(record)
      this.$refs.modalForm.title = '日营业详情'
    },
    handleChange(date, dateString) {
      this.queryParam.beginDate = dateString[0]
      this.queryParam.endDate = dateString[1]
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }

      if (!this.queryParam.endDate) {
        this.$message.warning('日期必选')
        return false
      }

      if (!this.queryParam.endDate) {
        this.$message.warning('日期必选')
        return false
      }

      let beginTime = this.orderDateRange[0]
      let endTime = this.orderDateRange[1]
      let diffDays = endTime.diff(beginTime, 'day')
      console.log('日期间隔天数', diffDays)
      if (diffDays > 31) {
        this.$message.warning('最多支持一个月跨度时间查询')
        return false
      }

      return true
    },
    searchQuery1() {
      if (!this.assembleQueryParam()) {
        return
      }

      this.loadData(1)
      this.querySum()
    },
    disabledDate(current) {
      console.log('current=', current)
      return current && current > moment().subtract(1, 'days')
    },
    searchReset1() {
      this.init()
    },
    querySum() {
      getAction(this.url.sumUrl, this.queryParam).then((res) => {
        if (res.success) {
          this.sumModel = res.result
        }
      })
    },
    handleExportXls1(fileName) {
      if (!this.assembleQueryParam()) {
        return
      }

      let total = this.ipagination.total
      if (total > 10000) {
        this.$message.warning('最多支持1万条数据导出')
        return false
      }

      this.handleExportXls(fileName)
    },
    handleExportSalesBill(fileName) {
      if (!this.assembleQueryParam()) {
        return
      }

      if(!this.queryParam.orgIds){
        this.$message.warning("市场必选")
        return false
      }

      this.exportVisible = true
    },
    handleCancel(){
      this.exportVisible = false
      this.confirmLoading = false
    },
    handleOk(){
      this.confirmLoading = true
      this.exportSalesBill('销售推账数据')
    },
    exportSalesBill(fileName){
      this.exporting = true
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      param['brandCode'] = this.exportModel.brandCode
      console.log('导出参数', param)
      let that = this
      downFile(this.url.exportSalesBillUrl, param).then((data) => {
        that.exporting = false

        that.handleCancel()
        if (!data) {
          that.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }

      })

      setTimeout(() => {
        that.exporting = false
        that.handleCancel()
      }, 20 * 1000)
    }
  },
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.sum {
  margin-right: 24px;
  .b {
    font-weight: 600;
    color: @primary-color;
  }
}
</style>